package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author LiaoLong
 * @date 2021-05-10 10:08
 */

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]>{

    private ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement ps, int index, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        String params = objectMapper.writeValueAsString(parameter);
        ps.setString(index, params);
    }

    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return transfer(result);
    }

    private Integer[] transfer(String result) {
        Integer[] integers = new Integer[0];
        if (result != null && !"".equals(result)) {
            try {
                integers = objectMapper.readValue(result, Integer[].class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return integers;
    }
}
